<script lang="ts" setup>
import type { AddDataType, DataType } from './types';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import {
  Button,
  message,
  Modal,
  Popconfirm,
  Space,
  Switch,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteModules,
  getModules,
  postModulesStatus,
  putMoudleSort
} from '#/api/portal/modules';
import Icon from '#/components/Icons';
import { resetRoutes } from '#/router';
import { toggleStatus } from '#/utils';

import { FormModalView, TableModalView } from './components';

defineOptions({
  name: 'PortalAdminModule',
});
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');
const typeEnum: any = { module: '模块', parameter: '参数', spec: '规格' };

const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    useKey: true,
    isCurrent: true,
    isHover: true,
    drag:true
  },
  columnConfig: {
    useKey: true,
  },
  treeConfig: {
    rowField: 'id',
    childrenField: 'children',
  },
  rowDragConfig:{
    isCrossDrag:true,
    showGuidesStatus:true,
    animation:true,
    dragEndMethod:function(res){
      putMoudleSort(res).then(response => {
      message.success(response.msg);  // 正确获取响应消息
     
    
    
    }).catch(error => {
      message.error(error.message);
    });
    return true;
    }
  },
  columns: [
  { field: 'id', title: $t('page.common.Code'), treeNode: true, align: 'left' , dragSort: true},
  { field: 'name', title: $t('admin.moduleName') },
  { field: 'code', title: $t('admin.moduleCode') },
  { field: 'description', title: $t('admin.moduleDescription') },
  { field: 'type', title: $t('page.common.Category'), slots: { default: 'type' } },
  { field: 'status', title: $t('page.common.Status'), slots: { default: 'status' } },
  { field: 'is_menu', title: $t('generateMenu'), slots: { default: 'is_menu' } },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: $t('page.common.Action'),
      width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    enabled: false,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        const { data } = await getModules({
          page: page.currentPage,
          limit: page.pageSize,
        });

        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const handleDelete = async (row: DataType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deleteModules(row.id);
    $table.remove(row);
    message.success(msg);
    resetRoutes();
  }
};

const onChange = async (row: AddDataType, type: 'menu' | 'status') => {
  Modal.confirm({
    title: $t('admin.systemMessage'),
    content: $t('admin.confirmAction'),
    async onOk() {
      try {
        await postModulesStatus({
          id: row.id,
          type,
        });
        message.success(`Success`);
        resetRoutes();
      } catch {
        if (type === 'status') row.status = toggleStatus(row.status);
        if (type === 'menu') row.is_menu = toggleStatus(row.is_menu);
      }
    },
    onCancel() {
      if (type === 'status') row.status = toggleStatus(row.status);
      if (type === 'menu') row.is_menu = toggleStatus(row.is_menu);
    },
  });
};

const [TableModal, tableModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: TableModalView,
});

const openMoreDialog = (title: string = '属性管理') => {
  const currentRecord = GridApi.grid.getCurrentRecord();
  if (!currentRecord) {
    message.error('未选择任何行！');
    return;
  }
  tableModalApi.setState({
    title: `${currentRecord?.name}--${viewTitle}${title}`,
  });

  tableModalApi.setData(currentRecord);
  tableModalApi.open();
};

const [FormModal, formModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FormModalView,
  onClosed() {
    const formModalData = formModalApi.getData();
    if (formModalData?.isUpdata) {
      GridApi.query();
      resetRoutes();
    }
  },
});

const openDialog = async (title: 'Add' | 'Edit', row?: DataType | null) => {
  formModalApi.setState({
    title: $t('page.common.'+title)+` ${viewTitle}`,
  });
  formModalApi.setData(row);
  formModalApi.open();
};
</script>

<template>
  <Page auto-content-height>
    <FormModal />
    <TableModal />
    <Grid :table-title="`${viewTitle} `+$t('page.common.List')">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openDialog('Add')">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          {{$t('page.common.Add')}} {{ viewTitle }}
        </Button>
        <Button class="mr-2" type="primary" @click="openMoreDialog()">
          <span class="anticon">
            <Icon icon="ri:menu-2-line" />
          </span>
          {{ viewTitle }} {{$t('admin.attributeManagement')}}
        </Button>
      </template>

      <template #type="{ row }">
        {{ typeEnum[row.type] }}
      </template>

      <template #status="{ row }">
        <Switch
          v-model:checked="row.status"
          :checked-value="1"
          :disabled="row.is_system === 1"
          :un-checked-value="0"
          :checked-children="$t('admin.Enable')"
          :un-checked-children="$t('admin.Disable')"
          @change="onChange(row, 'status')"
        />
      </template>

      <template #is_menu="{ row }">
        <Switch
          v-model:checked="row.is_menu"
          :checked-value="1"
          :disabled="
            row.is_system === 1 || !row.status || row.type !== 'module'
          "
          :un-checked-value="0"
          :checked-children="$t('page.common.Yes')"
          :un-checked-children="$t('page.common.No')"
          @change="onChange(row, 'menu')"
        />
      </template>

      <template #action="{ row }">
        <Space>
          <Button
            :disabled="row.is_system === 1"
            type="primary"
            @click="openDialog('Edit', row)"
          >
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            {{$t('page.common.Edit')}}
          </Button>
          <Popconfirm
            :disabled="row.is_system === 1"
            :cancel-text="$t('page.common.No')"
            :ok-text="$t('page.common.Yes')"
            :title="$t('page.common.Confirm Delete')"
            @confirm="handleDelete(row)"
          >
            <Button :disabled="row.is_system === 1" danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              {{$t('page.common.Delete')}}
            </Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
